package org.cyk.solution.demo;

class ListNode {
    int val;
    ListNode next;
    ListNode(int x) {
        val = x;
        next = null;
    }
}
public class SolutionJava {

    public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
        ListNode curA = headA;
        ListNode curB = headB;
        int sizeA = 0;
        int sizeB = 0;
        while(curA != null) {
            curA = curA.next;
            sizeA++;
        }
        while(curB != null) {
            curB = curB.next;
            sizeB++;
        }
        if(sizeA > sizeB) {
            int size = sizeA - sizeB;
            while(size > 0) {
                headA = headA.next;
                size--;
            }
        } else {
            int size = sizeB - sizeA;
            while(size > 0) {
                headB = headB.next;
                size--;
            }
        }
        while(headA != null && headB != null && headA != headB) {
            headA = headA.next;
            headB = headB.next;
        }
        if(headA == headB) {
            return headA;
        } else {
            return null;
        }
    }

}
